package com.infocollect.project.api.ui;

import com.infocollect.project.api.entity.TappDeptEntity;
import com.infocollect.project.api.entity.TappOrganEntity;
import com.infocollect.project.api.helper.CurrentHelp;
import com.infocollect.project.api.helper.MapHelper;
import com.infocollect.project.api.service.ITappDeptService;
import com.infocollect.project.api.service.ITappOrganService;
import com.infocollect.project.api.vo.CurrentUserInfoVO;
import com.infocollect.project.api.vo.OrganSearchVO;
import com.infocollect.project.form.vo.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * (TappOrgan)表控制层
 *
 * @author makejava
 * @since 2019-12-25 10:32:29
 */
@Api(value = "tappOrgan", tags = "机构信息")
@RestController
@RequestMapping("tappOrgan")
public class TappOrganController {
    /**
     * 服务对象
     */
    @Resource
    private ITappOrganService tappOrganService;
    /**
     * 服务对象
     */
    @Resource
    private ITappDeptService tappDeptService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation("获取机构信息")
    @PostMapping("selectOne/{id}")
    @ResponseBody
    public R<Object> selectOne(@PathVariable(name = "id") Long id) {

        return R.newOk(this.tappOrganService.queryById(id));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation("删除机构信息")
    @PostMapping("del/{id}")
    @ResponseBody
    public R<Object> Delete(@PathVariable(name = "id") Long id) {
        TappOrganEntity tappOrgan = new TappOrganEntity();
        tappOrgan.setFparentid(id);
        if (this.tappOrganService.queryAll(tappOrgan).size() > 0) {
            return R.newError("请先移除机构下的子机构！");
        } else {
            TappDeptEntity tappDept = new TappDeptEntity();
            tappDept.setForganid(id);
            if (this.tappDeptService.queryAll(tappDept).size() > 0) {
                return R.newError("请先移除机构下的部门！");
            } else {
                if (this.tappOrganService.deleteById(id)) {
                    return R.newOk();
                } else {
                    return R.newError("操作失败！");
                }
            }
        }
    }

    @ApiOperation("获取所有机构与部门信息")
    @PostMapping("GetALLOrganOrDept")
    public R<Object> GetALLOrganOrDept() {
        List<TappOrganEntity> organlist = tappOrganService.queryAll(null);
        List<TappDeptEntity> deptlist = tappDeptService.queryAll(null);
        return R.newOk(getChildResourceByPId(organlist, deptlist, null, "organ"));
    }

    /**
     * 递归组装菜单树
     *
     * @param
     * @param pId
     * @return
     */
    List<Map<String, Object>> getChildResourceByPId(List<TappOrganEntity> organlist, List<TappDeptEntity> deptlist, Long pId, String type) {
        List<Map<String, Object>> child = new ArrayList<>();
        if (type.equals("organ")) {
            System.out.println("pId：" + pId);
            organlist.forEach(ee -> {
                if (ee.getFparentid() != null && ee.getFparentid().equals(pId)) {
                    Map<String, Object> childitem = new HashMap<>();
                    childitem.put("fid", ee.getFid());
                    childitem.put("name", ee.getForganname());
                    childitem.put("index", ee.getForderindex());
                    childitem.put("code", ee.getForgancode());
                    childitem.put("typeid", "1");
                    childitem.put("procbid", pId);
                    childitem.put("ffax", ee.getFfax());
                    childitem.put("fphone", ee.getFphone());
                    childitem.put("faddress", ee.getFaddress());
                    childitem.put("children", getChildResourceByPId(organlist, deptlist, ee.getFid(), "organ"));
                    child.add(childitem);
                } else if (pId == null && ee.getFparentid() == null) {
                    Map<String, Object> childitem = new HashMap<>();
                    childitem.put("fid", ee.getFid());
                    childitem.put("name", ee.getForganname());
                    childitem.put("index", ee.getForderindex());
                    childitem.put("code", ee.getForgancode());
                    childitem.put("typeid", "1");
                    childitem.put("procbid", pId);
                    childitem.put("ffax", ee.getFfax());
                    childitem.put("fphone", ee.getFphone());
                    childitem.put("faddress", ee.getFaddress());
                    childitem.put("children", getChildResourceByPId(organlist, deptlist, ee.getFid(), "organ"));
                    child.add(childitem);
                }

            });
            if (pId != null) {
                deptlist.forEach(ee -> {
                    if (ee.getFparentid() == null && ee.getForganid().equals(pId)) {
                        Map<String, Object> childitem = new HashMap<>();
                        childitem.put("fid", ee.getFid());
                        childitem.put("name", ee.getFdeptname());
                        childitem.put("index", ee.getForderindex());
                        childitem.put("code", ee.getFdeptcode());
                        childitem.put("typeid", "2");
                        childitem.put("procbid", pId);
                        childitem.put("ffax", ee.getFfax());
                        childitem.put("fphone", ee.getFphone());
                        childitem.put("faddress", ee.getFaddress());
                        childitem.put("children", getChildResourceByPId(organlist, deptlist, ee.getFid(), "dept"));
                        child.add(childitem);
                    }
                });

            }
        } else {
            deptlist.forEach(ee -> {
                if (ee.getFparentid() != null && ee.getFparentid().equals(pId)) {
                    Map<String, Object> childitem = new HashMap<>();
                    childitem.put("fid", ee.getFid());
                    childitem.put("name", ee.getFdeptname());
                    childitem.put("index", ee.getForderindex());
                    childitem.put("code", ee.getFdeptcode());
                    childitem.put("typeid", "2");
                    childitem.put("procbid", pId);
                    childitem.put("ffax", ee.getFfax());
                    childitem.put("fphone", ee.getFphone());
                    childitem.put("faddress", ee.getFaddress());
                    childitem.put("children", getChildResourceByPId(organlist, deptlist, ee.getFid(), "dept"));
                    child.add(childitem);
                }
            });
        }
        return child;
    }

    /**
     * 保存机构信息
     *
     * @param
     * @return
     * @throws IOException
     */
    @ApiOperation("保存机构信息")
    @PostMapping("SaveOrgan")
    @ResponseBody
    public R<Object> SaveOrgan(@RequestBody Map<String, String> param) throws IOException {
        if (param.get("forganname") == null || param.get("forganname").length() == 0) {
            return R.newError("机构名称不能为空!");
        }
        if (param.get("fparentid") == null && param.get("fid") == null) {
            return R.newError("参数传入错误!");
        }
        if (param.get("forderindex") == null) {
            return R.newError("排序不能为空!");
        }
        try {
            TappOrganEntity entity = param.get("fid") == null ? null : this.tappOrganService.queryById(Long.parseLong(param.get("fid")));
            CurrentUserInfoVO currentUserInfo = CurrentHelp.Ins.GetUser();
            if (entity == null) {
                entity = new TappOrganEntity();
                entity.setFcreateby(currentUserInfo.getUserName());
                entity.setFlastupdateby(currentUserInfo.getUserName());
                entity.setFcreationdate(new Date());
                entity.setFlastupdatedate(new Date());
                MapHelper.setObjectValue(entity, param);
                entity.setForgancode(GetOrganCode(Long.parseLong(param.get("fparentid"))));
                entity.setFnum(0);
                entity.setFdeptnum(0);
                entity.setFstate("1");
                entity = this.tappOrganService.insert(entity);

            } else {
                entity.setFlastupdateby(currentUserInfo.getUserName());
                entity.setFlastupdatedate(new Date());
                MapHelper.setObjectValue(entity, param);
                entity = this.tappOrganService.update(entity);
            }
            return R.newOk(entity);
        } catch (Exception ex) {
            return R.newError("保存报错!具体错误信息为：" + ex.toString());
        }
    }

    String GetOrganCode(Long pid) {
        TappOrganEntity entity = this.tappOrganService.queryById(pid);
        entity.setFnum((entity.getFnum() == null ? 0 : entity.getFnum()) + 1);
        String code = "";
        for (int i = 0; i < 5 - entity.getFnum().toString().length(); i++) {
            code = code + "0";
        }
        this.tappOrganService.update(entity);
        return entity.getForgancode() + code + entity.getFnum().toString();
    }

    @ApiOperation("机构选择接口")
    @PostMapping("SelectOrgan/{Search}")
    @ResponseBody
    public R<List<OrganSearchVO>> SelectOrgan(@PathVariable(name = "Search") String search) throws Exception {

        List<OrganSearchVO> searchList = new ArrayList<>();
        List<TappOrganEntity> Organlist = new ArrayList<>();
        TappOrganEntity organEntity = null;
        search = search.equals("all") ? "10001" : search;
        organEntity = this.tappOrganService.queryByCode(search);
        Organlist = this.tappOrganService.queryByParentID(organEntity.getFid());

        TappOrganEntity parentOrganEntity = null;
        if (organEntity != null && organEntity.getFparentid() != null)
            parentOrganEntity = this.tappOrganService.queryById(organEntity.getFid());
        for (int i = 0; i < Organlist.size(); i++) {
            TappOrganEntity ee = Organlist.get(i);
            OrganSearchVO entity = new OrganSearchVO();
            entity.setNo(ee.getForgancode());
            entity.setName(ee.getForganname());
            entity.setIsDept(0);
            if (organEntity != null) {
                entity.setDeptPName(organEntity.getForganname());
                entity.setDeptPNo(organEntity.getForgancode());
                if (parentOrganEntity != null) {
                    entity.setGrandNo(parentOrganEntity.getForgancode());
                    entity.setGrandName(parentOrganEntity.getForganname());
                }
            }
            searchList.add(entity);
        }

        return R.newOk(searchList);
    }

    @ApiOperation("机构搜索")
    @PostMapping("SearchOrgan/{Search}")
    @ResponseBody
    public R<List<OrganSearchVO>> SearchOrgan(@PathVariable(name = "Search") String search) throws Exception {
        List<TappOrganEntity> OrganList = tappOrganService.queryNameOrCode(search);
        List<OrganSearchVO> searchList = new ArrayList<>();
        for (int i = 0; i < OrganList.size(); i++) {
            TappOrganEntity ee = OrganList.get(i);
            TappOrganEntity organEntity = tappOrganService.queryById(ee.getFid());
            OrganSearchVO entity = new OrganSearchVO();
            entity.setNo(ee.getForgancode());
            entity.setName(ee.getForganname());
            if (organEntity != null) {
                entity.setGrandNo(organEntity.getForgancode());
                entity.setGrandName(organEntity.getForganname());
                entity.setDeptPName(organEntity.getForganname());
                entity.setDeptPNo(organEntity.getForgancode());
            }
            entity.IsDept = 0;
            searchList.add(entity);
        }
        return R.newOk(searchList);

    }
}